package com.xue.handler;

import com.xue.UdpConnect;
import com.xue.domain.LocationInfo;
import com.xue.domain.LocationLightInfo;
import com.xue.geo.AreaControl;
import com.xue.geo.area.AreaJudge;
import com.xue.geo.domain.Coordinate;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

/**
 * @author xue
 * @create 2022-09-19 9:53
 */
@ChannelHandler.Sharable
public class LocationInfoHandler extends SimpleChannelInboundHandler<LocationInfo> {

    private final AreaControl areaControl = AreaControl.getInstance();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LocationInfo msg) throws Exception {
        AreaJudge areaJudge = areaControl.getAreaJudge();
        if (areaJudge != null) {
            Boolean inside = areaJudge.pointInside(new Coordinate(msg.getCoordinateX(), msg.getCoordinateY()));
            ByteBuf out = ctx.alloc().buffer();
            LocationLightInfo locationLightInfo = new LocationLightInfo(msg.getClassType(), msg.getId(), inside ? 1 : 2);
            ctx.writeAndFlush(new DatagramPacket(locationLightInfo.encoding(out), UdpConnect.ADDRESS));
        }
    }

}
